// import Config from '@/config'
import _ from 'lodash'
const getters = {
  userName: state => state.app.userName,
  username: state => state.app.username,
  token: state => state.app.token,
  dynamicsPage: state => state.app.dynamicsPage,
  version: state => state.app.version,
  refresh: state=> state.app.refresh,
  baseApi: state=> state.app.baseApi,
  role: state=> state.app.role,
  orgCode: state=> state.app.orgCode,
  number: state=> state.app.number,
  phone: state => {
    if (!state.app.phone) {
      let phone = localStorage.getItem('config-user-phone')
      if (phone) {
        state.app.phone = phone
      }
    }
    return state.app.phone
  },
  menuTree (state) {
    // 菜单树
    let rootMenuNode = {
      id: 0,
      children: []
    }
    console.log('xxxxx', state.app.menus)
    makeTree(rootMenuNode, state.app.menus)
    return rootMenuNode.children
  },
  dynamicsPageUrl (state) {
    return state.app.dynamicsPage.map(d => d.appUrl)
  },
  dynamicsPageAppName (state) {
    let data = state.app.dynamicsPage
    if (data && data.length > 0) {
     return  data.reduce((a, b) => {
        a[b.appUrl] = b.appName
        return a
      }, {})
    }
    return {}
  },
  menus (state) {
    return state.app.menus.map(d => {
      if (!d.parentId) {
        return d
      }
      return buildParentNode(d, state.app.menus)
    })
  },
  menuRoot (state) {
    // 根菜单
    return state.app.menus.filter(o => (_.isNil(o.parentId) || o.parentId === 'null' || o.parentId === '' || o.parentId === '0'))
  },
  appName: state => {
    if (state.app.appConfig && state.app.appConfig.sysName) {
      return state.app.appConfig.sysName
    }
    return '好店店管理系统'
  },
  appNameZw: state => {
    if (state.app.appConfig && state.app.appConfig.sysNameZw) {
      return state.app.appConfig.sysNameZw
    }
    return ''
  },
}

/**
 * 构造菜单树
 * @param {object} parentNode 父菜单节点
 * @param {menus[]} allMenus 菜单数组
 */
const makeTree = (parentNode, allMenus) => {
  const children = _.filter(
    allMenus,
    o => {
      if ((_.isNil(o.parentId) || o.parentId === 'null' || o.parentId === '') && parentNode.id === 0) {
        return true
      }
      return o.parentId === parentNode.id 
    }
  )
  _.forEach(children, function (child) {
    const node = {
      ...child,
      children: []
    }
    parentNode.children.push(node)
    makeTree(node, allMenus)
  })
}

// 构建父节点字段
const buildParentNode = (node, allMenus) => {
  let parent = allMenus.find(d => d.id === node.parentId)
  if (parent) {
    if (!parent.parents) {
      parent = buildParentNode(parent, allMenus)
    }
    node.parents = [...parent.parents, parent.menuName]
  } else {
    node.parents = []
  }
  return node
}

export default getters
